<template>
  <div class="canvas">
    <canvas
      ref="canvasF"
      @mousedown="mouseDown"
      @mousemove="mouseMove"
      @mouseup="mouseUp"
    ></canvas><br>
  </div>
</template>


<script>
import axios from "axios";

export default {
  name: "signature",
  data () {
    return {
      points: [],
      canvasTxt: null,
      startX: 0,
      startY: 0,
      moveY: 0,
      moveX: 0,
      endY: 0,
      endX: 0,
      w: null,
      h: null,
      isDown: false,
      color: "#000",
      linewidth: 3,
      isDraw: false //签名标记
    };
  },
  props:{
    session:'',
    student_id:''
  },
  mounted() {
    let canvas = this.$refs.canvasF;
    canvas.height = 320;
    canvas.width = 520;
    this.canvasTxt = canvas.getContext("2d");
    this.canvasTxt.strokeStyle = this.color;
    this.canvasTxt.lineWidth = this.linewidth;
  },
  methods:{
    mouseDown(ev) {
      ev = ev || event;
      ev.preventDefault();
      let obj = {
        x: ev.offsetX,
        y: ev.offsetY
      };
      this.startX = obj.x;
      this.startY = obj.y;
      this.canvasTxt.beginPath();//开始作画
      this.points.push(obj);//记录点
      this.isDown = true;
    },
    mouseMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (this.isDown) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.moveTo(this.startX, this.startY);//移动画笔
        this.canvasTxt.lineTo(obj.x, obj.y);//创建线条
        this.canvasTxt.stroke();//画线
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);//记录点
      }
    },
    mouseUp(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        };
        this.canvasTxt.closePath();//收笔
        this.points.push(obj);//记录点
        this.points.push({ x: -1, y: -1 });
        this.isDown = false;
      }
    },
    overwrite() {
      this.canvasTxt.clearRect(
        0,
        0,
        this.$refs.canvasF.width,
        this.$refs.canvasF.height
      );
      this.points = [];
      this.isDraw = false; //签名标记
    },
    async save(){
      let params={
        session_key:this.session,
        student_id:this.student_id,
        sign_base:this.$refs.canvasF.toDataURL('image/png')
      }
      const res = await axios.post('/api/api/api/saveSign',params)
      const {data,msg,code}=res.data
      if (code==200){
        this.$message.success(msg)
      }
    },
  },

}
</script>

<style scoped>
canvas{
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}
</style>
